<template>
	<view style="width: 100%;">
		<view class="gui-bg-white gui-dark-bg-level-3 gui-padding" style="width: 100%;word-break: break-all;">
			<!-- 文章标题 -->
			<view class="gui-padding gui-text-center" v-if="mid!=0">
				<text class="gui-h3 gui-bold">{{info.title}}</text>

			</view>

			<view style="width:100%">

				
				<!-- 使用 u-parse 组件显示富文本内容 -->
				<u-parse v-if="html" :content="html" @preview="preview" @navigate="navigate"></u-parse>
				
				<!-- 备用 rich-text 组件 -->
				<rich-text v-else-if="article.length" :preview="true" :selectable="true" @itemclick="itemclick" id="cs" class="html_content"
					:nodes="article"></rich-text>
			</view>
			<view class="gui-text gui-color-gray d-flex jc-between">
				<text style="text-align: left;">来源：{{info.resource}}</text>
				<text class="" style="margin-top: 10rpx;">{{info.look_num}}次观看</text>
			</view>

		</view>
		<view v-if="info.is_btn==1" class="p-20">

			<button :style="btn_style" @click="btn_url()">{{info.btn_json.text}}</button>
		</view>


		<!-- 点赞和评论操作栏 -->
		<view class="action-bar gui-bg-white" v-if="info.allow_like==1 || info.allow_comment==1">
			<view class="action-item" @click="toggleLike" v-if="info.allow_like==1">

				<text class="action-icon" :class="{'liked': isLiked}">
					<text class="gui-icons px-10">&#xe6ea;</text>
					点赞</text>
				<text class="action-text">{{likeCount}}</text>
			</view>
			<view class="action-item" v-if="info.allow_comment==1" @click="showCommentInput = !showCommentInput">
				<text class="action-icon">
					<text class="gui-icons px-10">&#xe6b8; </text>
					评论</text>
				<text class="action-text">{{commentCount}}</text>
			</view>

		</view>


		<!-- 评论输入框 -->
		<view class="comment-input-section gui-bg-white" v-if="info.allow_comment==1">
			<view class="comment-input-wrapper">
				<input class="comment-input" v-model="commentText" placeholder="写下你的评论..." maxlength="200"
					@confirm="submitComment" />
				<button class="comment-submit-btn" @click="submitComment" :disabled="!commentText.trim()">
					发送
				</button>
			</view>
		</view>

		<!-- 评论列表 -->
		<view class="comment-section gui-bg-white" v-if="info.allow_comment==1">
			<view class="comment-title">
				<text class="gui-h5 gui-color-gray">评论 ({{commentCount}})</text>
			</view>
			<view class="comment-list">
				<view class="comment-item" v-for="(comment, index) in commentList" :key="index">
					<view class="comment-header">
						<view class="comment-user-info">

							<text class="comment-author">{{comment.user.real_name || '匿名用户'}}</text>
							<text class="comment-time">{{comment.crt_time}}</text>
						</view>
						<view class="comment-actions" v-if="comment.user_id==user.id">
							<text class="delete-btn" @click="deleteComment(comment.id, index)">删除</text>
						</view>
					</view>
					<view class="comment-content">
						<text>{{comment.content}}</text>
					</view>
				</view>
				<view class="no-comment" v-if="commentList.length === 0">
					<text class="gui-color-gray">暂无评论，快来抢沙发吧~</text>
				</view>
			</view>
		</view>

		<!-- 积分提示弹窗 -->
		<view class="point-toast" v-if="showPointToast">
			<view class="point-toast-content">
				<text class="point-icon">🎉</text>
				<text class="point-text">{{pointMessage}}</text>
			</view>
		</view>
	</view>
</template>
<script>
	import parserHtml from "@/Grace6/js/parserHTML.js";
	import uParse from '@/components/u-parse/u-parse.vue'
	import config from '@/config.js'

	export default {
		data() {
			return {
				article: [],
				html: '',
				mid: 0,
				baseimg: 'https://app.lgwisdomunion.cn',
				info: {
					title: '',
					lookNum: 0,
					author: ''
				},
				imgs: [],
				// 新增数据
				isLiked: false,
				likeCount: 0,
				commentCount: 0,
				showCommentInput: false,
				commentText: '',
				commentList: [],
				showPointToast: false,
				pointMessage: '',
				hasGotReadPoints: false, // 是否已获得阅读积分
				user: uni.getStorageSync("userInfo"),
				btn_style: {}
			}
		},
		onLoad: function(opt) {
			let self = this;
			uni.showLoading({
				title: "loading",
				mask: true
			});

			// 打印接收到的所有参数
			console.log("=== 新闻详情页接收参数 ===");
			console.log("完整参数对象:", opt);
			console.log("参数类型:", typeof opt);
			console.log("参数键值对:");
			for (let key in opt) {
				console.log(`${key}: ${opt[key]} (类型: ${typeof opt[key]})`);
			}
			console.log("=== 参数打印结束 ===");

			console.log("opt", opt.id);
			if (opt.hasOwnProperty("id")) {
				uni.setNavigationBarTitle({
					title: '新闻详情'
				});
				self.mid = opt.id
				console.log("新闻ID:", self.mid);
				console.log("新闻ID类型:", typeof self.mid);
				this.newsInfo();
				this.loadComments();
				this.checkLikeStatus();
			}
			if (opt.hasOwnProperty("agreements")) {
				uni.setNavigationBarTitle({
					title: '加载中。。'
				});
				this.agreements(opt.agreements);
			}
		},

		onShow() {
			console.log("=== 新闻详情页 onShow ===");
			console.log("当前新闻ID:", this.mid);
			console.log("是否已获得阅读积分:", this.hasGotReadPoints);
			console.log("=== onShow 结束 ===");
			
			// 页面显示时给予阅读积分
			if (this.mid && !this.hasGotReadPoints) {
				this.giveReadPoints();
			}
		},

		methods: {
			btn_url() {
				this.$comm.nav_to(this.info.btn_json.url)
			},
					preview(e) {
			console.log("u-parse preview事件:", e);
		},
		navigate(e) {
			console.log("u-parse navigate事件:", e);
		},
			newsInfo() {
				let self = this;
				this.imgs = [];
				
				console.log("=== 开始获取新闻详情 ===");
				console.log("请求参数 - id:", self.mid);
				console.log("请求参数类型:", typeof self.mid);
				console.log("请求URL:", "/lgzhsys/newsInfo");
				console.log("请求数据:", { "id": self.mid });
				
				this.$boya.NGet("/lgzhsys/newsInfo", {
					"id": self.mid
				}, function(res) {
					console.log("=== 新闻详情接口返回 ===");
					console.log("完整返回数据:", res);
					console.log("返回数据类型:", typeof res);
					console.log("新闻详情数据:", res.data);
					console.log("res.data.content:", res.data.content);
					console.log("res.data.content类型:", typeof res.data.content);
					console.log("res.data.content长度:", res.data.content ? res.data.content.length : 0);
					console.log("=== 新闻详情数据结束 ===");
					
					self.info = res.data;
					// 根据配置决定是否允许评论
					if (!config.open_comment) {
						self.info.allow_comment = 0;
					}
					
					if (self.info.is_btn == 1) {
						self.info.btn_json = JSON.parse(self.info.btn_json)
						if (self.info.btn_json.hasOwnProperty("style")) {
							self.btn_style = self.info.btn_json.style;
						}
					}
					console.log("info", self.info);
					uni.setNavigationBarTitle({
						title: res.data.title
					})
					let html = res.data.content;
					console.log("原始content:", res.data.content);
					console.log("content类型:", typeof res.data.content);
					console.log("content是否为空:", !res.data.content);
					console.log("config.open_comment:", config.open_comment);
					
					if (html) {
						html = html.replace(/src="\/API-RESOURCE\//g,
							'src="https://app.lgwisdomunion.cn/API-RESOURCE/');
						// 设置html变量供u-parse使用
						self.html = html;
						// 尝试解析HTML
						try {
							let _article = parserHtml.parserHTML(html);
							// 处理图片路径和样式
							for (let i in _article) {
								let m = _article[i].children
								for (let key in m) {
									let c = m[key].attrs
									if (!c) continue;
									if (c.hasOwnProperty("src")) {
										let imgpath = c.src;
										if (imgpath.indexOf("//") == -1) {
											imgpath = self.baseimg + c.src;
										}
										_article[i].children[key].attrs.src = imgpath;
										_article[i].children[key].attrs.style = "width:100%";
										self.imgs.push(c.src)
									}
								}
							}
							self.article = _article;
						} catch (error) {
							self.article = [];
						}
					} else {
						self.html = '';
					}

					// 设置点赞和评论数量
					self.likeCount = res.data.like_count || 0;
					self.commentCount = res.data.comment_count || 0;

					uni.hideLoading();
				}, function(err) {
					console.error("获取新闻详情失败:", err);
					uni.hideLoading();
					uni.showToast({
						title: '获取新闻详情失败',
						icon: 'none'
					});
				})

			},
			agreements(n) {
				let self = this;

				this.$boya.NGet('/agreements/' + n, {}, function(res) {
					self.html = res.data.content
					// self.article=parserHtml.parserHTML(res.data.content);
					// self.article.map(function(item,index){
					// 	console.log(index,item);
					// })
					uni.setNavigationBarTitle({
						title: res.data.name
					})
					uni.hideLoading();
				}, null, {
					CheckToken: false
				});
			},
			itemclick(node) {
				console.log(node);
				if (node.detail.node.name == "img") {
					this.preview(node.detail.node.attrs.src);
				}
			},
			preview(img) {
				let index = this.imgs.indexOf(img);
				uni.previewImage({
					urls: this.imgs,
					index: index
				})
			},

			// 新增方法：点赞功能
			toggleLike() {
				if (this.isLiked) {
					this.unlikeNews();
				} else {
					this.likeNews();
				}
			},

			// 点赞新闻
			async likeNews() {
				try {
					if (this.isLiked) {
						// 取消点赞
						await this.$boya.NPost("/app/news/unlike", {
							news_id: this.mid
						});
						this.isLiked = false;
						this.likeCount = Math.max(0, this.likeCount - 1);

						// 扣除点赞积分
						try {
							const deductResult = await this.$boya.NPost("/app/news/deduct_like_points", {
								news_id: this.mid
							});
							if (deductResult.data.deducted_points > 0) {
								this.showPointMessage(`取消点赞，扣除 ${deductResult.data.deducted_points} 积分`, 'warning');
							}
						} catch (err) {
							console.log('扣除点赞积分失败:', err);
						}
					} else {
						// 点赞
						await this.$boya.NPost("/app/news/like", {
							news_id: this.mid
						});
						this.isLiked = true;
						this.likeCount++;

						// 发放点赞积分
						try {
							const pointResult = await this.$boya.NPost("/app/points/like", {
								related_id: this.mid,
								content_type: 'news'
							});
							if (pointResult.points > 0) {
								this.showPointMessage(`点赞获得 ${pointResult.points} 积分`);
							}
						} catch (err) {
							console.log('点赞积分发放失败:', err);
						}
					}
				} catch (error) {
					console.error('点赞操作失败:', error);
					uni.showToast({
						title: '操作失败，请稍后再试',
						icon: 'none'
					});
				}
			},

			// 取消点赞
			unlikeNews() {
				let self = this;
				this.$boya.NPost("/app/news/unlike", {
					news_id: self.mid
				}, function(res) {
					self.isLiked = false;
					self.likeCount--;

					if (res.data.deducted_points && res.data.deducted_points > 0) {
						self.showPointMessage(`取消点赞成功！扣除${res.data.deducted_points}积分`);
					} else {
						self.showPointMessage('取消点赞成功！');
					}
				}, function(err) {
					uni.showToast({
						title: err.message || '取消点赞失败',
						icon: 'none'
					});
				});
			},

			// 检查点赞状态
			checkLikeStatus() {
				let self = this;
				this.$boya.NGet("/app/news/like_status", {
					news_id: self.mid
				}, function(res) {
					self.isLiked = res.data.is_liked || false;
				});
			},

			// 提交评论
			submitComment() {
				let self=this;
				if (!this.commentText.trim()) {
					uni.showToast({
						title: '请输入评论内容',
						icon: 'none'
					});
					return;
				}


				this.$boya.NPost("/app/news/comment", {
					news_id: this.mid,
					content: this.commentText.trim()
				}, function(result) {

					// 添加到评论列表
					self.commentList.unshift({
						id: result.comment_id,
						content: self.commentText.trim(),
						user_name: '我', // 当前用户
						created_at: new Date().toISOString(),
						is_mine: true
					});

					self.commentText = '';
					self.showCommentInput = false;
					self.commentCount++;
					self.loadComments();
					self.showPointMessage('评论发表成功');

					// 发放评论积分

					self.$boya.NPost("/app/points/comment", {
							related_id: self.mid
						}, function(pointResult) {
							if (pointResult.points > 0) {
								self.showPointMessage(`评论获得 ${pointResult.points} 积分`);
							}
						},
						function(err) {
							console.log('评论积分发放失败:', err);
						});

				},function(err){
					console.log("err",err);
					uni.showToast({
						title:err.msg,
						icon:"none",
						duration:3000
					})
				});


			},

			// 加载评论列表
			loadComments() {
				let self = this;
				this.$boya.NGet("/app/news/comments", {
					news_id: self.mid,
					limit: 20
				}, function(res) {
					self.commentList = res.data.data || [];
					self.commentCount = res.data.total;
				});
			},

			// 分享新闻
			shareNews() {
				let self = this;
				uni.share({
					provider: "weixin",
					scene: "WXSceneSession",
					type: 0,
					href: `https://app.lgwisdomunion.cn/news/${self.mid}`,
					title: self.info.title,
					summary: "来自工会智慧联盟的精彩内容",
					imageUrl: "https://app.lgwisdomunion.cn/logo.png",
					success: function(res) {
						self.showPointMessage('分享成功！获得积分奖励');
						// 调用积分接口
						self.giveSharePoints();
					},
					fail: function(err) {
						console.log("分享失败：" + JSON.stringify(err));
					}
				});
			},

			// 格式化时间
			formatTime(time) {
				if (!time) return '';
				const date = new Date(time);
				const now = new Date();
				const diff = now - date;

				if (diff < 60000) { // 1分钟内
					return '刚刚';
				} else if (diff < 3600000) { // 1小时内
					return Math.floor(diff / 60000) + '分钟前';
				} else if (diff < 86400000) { // 1天内
					return Math.floor(diff / 3600000) + '小时前';
				} else {
					return date.getMonth() + 1 + '-' + date.getDate();
				}
			},

			// 显示积分提示
			showPointMessage(message) {
				this.pointMessage = message;
				this.showPointToast = true;
				setTimeout(() => {
					this.showPointToast = false;
				}, 2000);
			},

			// 阅读积分
			giveReadPoints() {
				let self = this;
				this.$boya.NPost("/app/points/read", {
					news_id: self.mid
				}, function(res) {
					if (res.points > 0) {
						self.showPointMessage(`阅读奖励：+${res.points}积分`);
					}
					self.hasGotReadPoints = true;
				}, function(err) {
					// 静默处理错误，不影响用户体验
					console.log('阅读积分获取失败：', err);
					self.hasGotReadPoints = true;
				});
			},

			// 点赞积分
			giveLikePoints() {
				let self = this;
				this.$boya.NPost("/app/points/like", {
					related_id: self.mid
				}, function(res) {
					if (res.points > 0) {
						self.showPointMessage(`点赞奖励：+${res.points}积分`);
					}
				}, function(err) {
					console.log('点赞积分获取失败：', err);
				});
			},

			// 评论积分
			giveCommentPoints(commentId) {
				let self = this;
				this.$boya.NPost("/app/points/comment", {
					related_id: self.mid
				}, function(res) {
					if (res.points > 0) {
						self.showPointMessage(`评论奖励：+${res.points}积分`);
					}
				}, function(err) {
					console.log('评论积分获取失败：', err);
				});
			},

			// 分享积分
			giveSharePoints() {
				let self = this;
				this.$boya.NPost("/app/points/share", {
					related_id: self.mid
				}, function(res) {
					if (res.points > 0) {
						self.showPointMessage(`分享奖励：+${res.points}积分`);
					}
				}, function(err) {
					console.log('分享积分获取失败：', err);
				});
			},

			// 删除评论
			deleteComment(commentId, index) {
				let self = this;
				uni.showModal({
					title: '确认删除',
					content: '删除评论后将扣除相应积分，确定要删除吗？',
					success: function(res) {
						if (res.confirm) {
							self.$boya.NPost("/app/news/comment_delete", {
								comment_id: commentId
							}, function(res) {
								self.commentList.splice(index, 1);
								self.commentCount--;

								if (res.data.deducted_points && res.data.deducted_points >
									0) {
									self.showPointMessage(
										`评论删除成功！扣除${res.data.deducted_points}积分`);
								} else {
									self.showPointMessage('评论删除成功！');
								}
							}, function(err) {
								uni.showToast({
									title: err.message || '评论删除失败',
									icon: 'none'
								});
							});
						}
					}
				});
			}
		}
	}
</script>
<style>
	/* * {
		margin: 0 auto;
	} */

	image {
		width: 100%;
		/* margin-left: -72rpx; */
	}

	img {
		width: 100%;
		/* margin-left: -71rpx; */
	}

	.rich {
		padding: 0;
		line-height: 65rpx;
		font-size: 36rpx;
		text-indent: 72rpx;
		/* font-family: "宋体"; */
	}

	.html_content {
		width: 100%;
		line-height: 72rpx;
		font-size: 36rpx;
		color: #555555;
	}

	.html_content image {
		width: 100%;
		max-width: 100%;
		height: auto;
	}

	/* 新增样式 */
	.action-bar {
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 20rpx 0;
		border-top: 1rpx solid #f0f0f0;
		border-bottom: 1rpx solid #f0f0f0;
		margin-top: 20rpx;
	}

	.action-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 10rpx 20rpx;
		cursor: pointer;
		gap: 10rpx;
	}

	.action-icon {

		margin-bottom: 8rpx;
		color: #666;
		transition: color 0.3s;
	}

	.action-icon.liked {
		color: #ff4757;
	}

	.action-text {
		font-size: 24rpx;
		color: #999;
	}

	.comment-input-section {
		padding: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.comment-input-wrapper {
		display: flex;
		align-items: center;
		background: #f8f9fa;
		border-radius: 25rpx;
		padding: 10rpx 20rpx;
	}

	.comment-input {
		flex: 1;
		border: none;
		background: transparent;
		font-size: 28rpx;
		padding: 10rpx 0;
	}

	.comment-submit-btn {
		background: #007aff;
		color: white;
		border: none;
		border-radius: 20rpx;
		padding: 8rpx 20rpx;
		font-size: 24rpx;
		margin-left: 10rpx;
	}

	.comment-submit-btn[disabled] {
		background: #ccc;
	}

	.comment-section {
		padding: 20rpx;
	}

	.comment-title {
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.comment-item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f8f9fa;
	}

	.comment-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.comment-user-info {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.comment-actions {
		display: flex;
		align-items: center;
	}

	.delete-btn {
		color: #ff4757;
		font-size: 24rpx;
		padding: 5rpx 10rpx;
		border-radius: 4rpx;
		background: #fff5f5;
		border: 1rpx solid #ffebee;
	}

	.comment-author {
		font-size: 26rpx;
		color: #999;
		font-weight: bold;
	}

	.comment-time {
		font-size: 22rpx;
		color: #999;
	}

	.comment-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
	}

	.no-comment {
		text-align: center;
		padding: 60rpx 0;
	}

	.point-toast {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 9999;
		background: rgba(0, 0, 0, 0.8);
		border-radius: 10rpx;
		padding: 20rpx 40rpx;
		animation: fadeInOut 2s ease-in-out;
	}

	.point-toast-content {
		display: flex;
		align-items: center;
		color: white;
	}

	.point-icon {
		font-size: 32rpx;
		margin-right: 10rpx;
	}

	.point-text {
		font-size: 28rpx;
	}

	@keyframes fadeInOut {
		0% {
			opacity: 0;
			transform: translate(-50%, -50%) scale(0.8);
		}

		20% {
			opacity: 1;
			transform: translate(-50%, -50%) scale(1);
		}

		80% {
			opacity: 1;
			transform: translate(-50%, -50%) scale(1);
		}

		100% {
			opacity: 0;
			transform: translate(-50%, -50%) scale(0.8);
		}
	}
</style>